package com.ruoyi.web.controller.persona;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.smartai.service.IDialogueService;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.IFansInfoService;
import com.ruoyi.system.service.ICustomerInfoService;
import com.ruoyi.system.service.impl.StatusCheckService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 粉丝
 */
@RestController
@RequestMapping("/persona/fans")
public class FansInfoController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(FansInfoController.class);


    @Autowired
    private Environment env;

    @Autowired
    private IFansInfoService fansInfoService;

    @Autowired
    private ICustomerInfoService cusUserService;

    @Autowired
    private StatusCheckService statusCheckService;

    @Autowired
    private IDialogueService iDialogueService;

    @Autowired
    private RedisCache redisCache;

    @Value("${devicesPath.clinetBluk}")
    private String clinetBluk;

    @Value("${devicesPath.syncBook}")
    private String syncBook;

    @Value("${apiSevicePath.secketSendmessage}")
    private String newChatURL;


    @PreAuthorize("@ss.hasPermi('client:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(FansInfo fansInfo) {
        startPage();
//        LoginUser loginUser = getLoginUser();
//        SysUser sysUser =loginUser.getUser();
//        if (sysUser.getUserName().equals("A001")){
//            fansInfo.setTemplateId("103");
//        }
        List<FansInfo> list = fansInfoService.selectChatList(fansInfo);
        return getDataTable(list);
    }

    @Log(title = "客服管理", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('client:user:edit')")
    @PutMapping()
    public AjaxResult edit(@Validated @RequestBody FansInfo fansInfo) {
        CustomerInfo cusUser = cusUserService.selectUserByNumber(fansInfo.getCustomerNumber());
        if (StringUtils.isNull(cusUser)) {
            return error("客服不存在");
        }
        fansInfo.setUserId(cusUser.getUserId());
        fansInfo.setDeptId(cusUser.getDeptId());
        return toAjax(fansInfoService.updateCustomerChat(fansInfo));
    }

    @PreAuthorize("@ss.hasPermi('client:user:edit')")
    @GetMapping(value = "/{id}")
    public AjaxResult getCustomer(@PathVariable String id) {
        return success(fansInfoService.selectChatById(id));
    }

    /**
     * 新增粉丝
     */
    @PreAuthorize("@ss.hasPermi('client:user:add')")
    @Log(title = "粉丝管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody FansInfo user) {
        if (StringUtils.isEmpty(user.getCustomerNumber())) {
            return error("粉丝专属坐席号码不能为空");
        }
        FansInfo chatU = fansInfoService.selectChatByClientNumber(user.getClientNumber());
        if (StringUtils.isNotNull(chatU)) {
            return error("粉丝号码已存在");
        }
        CustomerInfo cusUser = cusUserService.selectUserByNumber(user.getCustomerNumber());
        if (StringUtils.isNull(cusUser)) {
            return error("客服不存在");
        }
        user.setUserId(cusUser.getUserId());
        user.setDeptId(cusUser.getDeptId());
        return toAjax(fansInfoService.insertUser(user));
    }

    @PreAuthorize("@ss.hasPermi('client:user:bulk')")
    @Log(title = "群发", businessType = BusinessType.INSERT)
    @PostMapping("/bulk")
    public AjaxResult bulk(@Validated @RequestBody BulkMessage bulkMessage) {
        if (StringUtils.isNull(bulkMessage)) {
            return error("群发内容为空");
        }
        if (StringUtils.isNull(bulkMessage.getIds())) {
            return error("粉丝账户不存在");
        }

        int status = fansInfoService.bulkMessage(bulkMessage);

        return success(status);
    }

    /**
     * 删除坐席
     */
    @PreAuthorize("@ss.hasPermi('client:user:remove')")
    @Log(title = "坐席管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable String[] id) {
        return toAjax(fansInfoService.deleteUserByNumbers(id));
    }

    @Log(title = "导入", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('client:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<FansInfo> util = new ExcelUtil<FansInfo>(FansInfo.class);
        List<FansInfo> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = fansInfoService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @Log(title = "导出", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('client:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, FansInfo user) {
        List<FansInfo> list = fansInfoService.selectChatList(user);
        ExcelUtil<FansInfo> util = new ExcelUtil<FansInfo>(FansInfo.class);
        util.exportExcel(response, list, "whatsapp数据");
    }


    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<FansInfo> util = new ExcelUtil<FansInfo>(FansInfo.class);
        util.importTemplateExcel(response, "whatsapp数据");
    }

    @PreAuthorize("@ss.hasPermi('client:user:init')")
    @GetMapping("/clientInit")
    public AjaxResult clientInit() {
        log.info("----------------  autoChat  autoChat-------------------");
        String rspStr = HttpUtils.sendGet(env.getProperty("apiSevicePath.autoChat"));
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", rspStr);
        return ajax;
    }

    @PreAuthorize("@ss.hasPermi('customer:user:chat')")
    @GetMapping("/clientChat/{id}")
    public AjaxResult clientChat(@PathVariable("id") String id) {
        log.info("----------------  autoChat  newChat-------------------:" + newChatURL);
        String rspStr = HttpUtils.sendGet(newChatURL + id);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", rspStr);

        return ajax;
    }

    /**
     * 获取登录二维码
     */
    @PreAuthorize("@ss.hasPermi('customer:user:auto')")
    @GetMapping("/autoChat/{id}")
    public AjaxResult createClient(@PathVariable("id") String id) {
        String rspStr = HttpUtils.sendGet(env.getProperty("apiSevicePath.auto_Chat") + id);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", rspStr);
        return ajax;
    }


    @PreAuthorize("@ss.hasPermi('customer:user:syncBook')")
    @PostMapping("/syncBook")
    public AjaxResult syncBook(@RequestBody BulkSendName bulkSendName) throws UnsupportedEncodingException {
        log.info("----------------  autoChat  syncBook-------------------:" + syncBook);
        String param = "?";
        // 假设getId()返回的是ID列表，使用String.join()将它们以逗号分隔
        String ids = String.join(",", bulkSendName.getId());
        param += "id=" + ids;
        String rspStr = HttpUtils.sendGet(syncBook + param);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", rspStr);

        return ajax;
    }

    @PreAuthorize("@ss.hasPermi('customer:user:chat')")
    @GetMapping("/startChat/{id}")
    public AjaxResult startChat(@PathVariable("id") String[] id) {
        log.info("----------------  autoChat  startChat-------------------:" + newChatURL);
//        String rspStr = HttpUtils.sendGet(newChatURL + id);
        AjaxResult ajax = AjaxResult.success();
        int data = iDialogueService.startForFansIds(id, newChatURL);
        ajax.put("data", data);
        return ajax;
    }

    @PreAuthorize("@ss.hasPermi('customer:user:chat')")
    @PostMapping("/clinetBluk")
    public AjaxResult clinetBluk(@RequestBody BulkSendName bulkSendName) {
        log.info("----------------  autoChat  clinetBluk-------------------:" + clinetBluk);

        AjaxResult ajax = AjaxResult.success();
        int data = iDialogueService.sendBlukByFansId(bulkSendName.getId(), newChatURL, bulkSendName.getMessage(), bulkSendName.getMessageType());
        ajax.put("data", data);
        return ajax;
    }

    @PreAuthorize("@ss.hasPermi('customer:user:chat')")
    @GetMapping("/pauseChat/{id}")
    public AjaxResult pauseChat(@PathVariable("id") String[] id) {
        fansInfoService.pauseChat(id, 1);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", 1);
        return ajax;
    }

    @PreAuthorize("@ss.hasPermi('customer:user:chat')")
    @GetMapping("/resumeChat/{id}")
    public AjaxResult resumeChat(@PathVariable("id") String[] id) {
        fansInfoService.pauseChat(id, 0);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", 1);
        return ajax;
    }

    @PreAuthorize("@ss.hasPermi('customer:user:chat')")
    @GetMapping("/chat/list/{customerNumber}")
    public AjaxResult chatBoxList(@PathVariable("customerNumber") String customerNumber) {
        if ("null".equals(customerNumber))
            customerNumber = null;
        List<ChatBoxInfo> chatboxList = fansInfoService.getChatBoxList(customerNumber);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", chatboxList);
        return ajax;
    }

    @PreAuthorize("@ss.hasPermi('customer:user:chat')")
    @GetMapping("/updateManual")
    public AjaxResult updateManual(@RequestParam("fansId") String fansId, @RequestParam("statics") String statics) {
        fansInfoService.updateManualService(fansId, statics);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", 1);
        return ajax;
    }

    @PreAuthorize("@ss.hasPermi('customer:user:chat')")
    @GetMapping("/getManual/{fansId}")
    public AjaxResult getManual(@PathVariable("fansId") String fansId) {
        FansInfo fansInfo = fansInfoService.selectChatByClientNumber(fansId);
        String trans = redisCache.getCacheObject("persona:fans:" + fansId + ":language");
        fansInfo.setLanguage(trans);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", fansInfo);
        return ajax;
    }

    @PreAuthorize("@ss.hasPermi('customer:user:chat')")
    @GetMapping("/unread/{fansId}")
    public AjaxResult setUnread(@PathVariable("fansId") String fansId) {
        String key = "persona:fans:" + fansId + ":unread";
        redisCache.setCacheObject(key,0);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", fansId);
        return ajax;
    }




}
